package com.atguigu.yuntai.govern.parser;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hive.ql.parse.ASTNode;

import java.util.ArrayList;
import java.util.List;

@Data
public class WhereObj {

    List<ConditionPair> conditionPairList = new ArrayList<>();

    public WhereObj(ASTNode astNode) {
        handleWhere(astNode);
    }

    private void handleWhere(ASTNode astNode) {
        for (int i = 0; i < astNode.getChildCount(); i++) {
            if ("=".equals(astNode.getChild(i).getText())) {
                handleEquality((ASTNode) astNode.getChild(i));
            } else if ("in".equals(astNode.getChild(i).getText())) {
                handleIn((ASTNode) astNode.getChild(i));
            } else {
                handleWhere((ASTNode) astNode.getChild(i));
            }

        }

    }

    private void handleEquality(ASTNode equalityTree) {
        FieldObj fieldObj1 = new FieldObj(equalityTree.getChild(0));
        if (equalityTree.getChild(1).equals("TOK_TABLE_OR_COL")) {
            FieldObj fieldObj2 = new FieldObj(equalityTree.getChild(1));
            conditionPairList.add(new ConditionPair(fieldObj1, fieldObj2, null));
        } else {
            String value = equalityTree.getChild(1).getText();
            conditionPairList.add(new ConditionPair(fieldObj1, null, value));
        }

    }

    private void handleIn(ASTNode inTree) {
        ASTNode inFunctionNode = (ASTNode) inTree.getParent();
        FieldObj fieldObj1 = new FieldObj(inFunctionNode.getChild(1));
        List<String> valueList = new ArrayList<>();
        for (int i = 2; i < inFunctionNode.getChildCount(); i++) {
            valueList.add(inFunctionNode.getChild(i).getText());
        }
        String inValue = StringUtils.join(valueList, ",");
        conditionPairList.add(new ConditionPair(fieldObj1, null, inValue));

    }

    @Data
    @AllArgsConstructor
    public class ConditionPair {
        FieldObj fieldObj1;
        FieldObj fieldObj2;
        String value;

    }

}
